package com.atguigu.demo02.test01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gjl
 * @create 2021-04-25 12:55
 */
public class Print {
    int number = 1;
    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void printThree(){


            for (int i = 1; i <= 3; i++) {
                try {
                    //判断
                    while (number != i){
                        condition.await();
                    }
                    for (int j = 1; j <= i * 5; j++) {
                        //干活
                        System.out.println(Thread.currentThread().getName()+"  "+j);
                    }
                    number = i+1;
                    if (i==3){
                        number = 1;
                    }
                    condition.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }

    }

    public void print1() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (number !=1){ //while
                condition1.await();
            }
            //干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+i);
            }
            //通知
            number = 2;
            condition2.signal();
        } finally {
            lock.unlock();
        }
    }
    public void print2() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (number !=2){ //while
                condition2.await();
            }
            //干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+i);
            }
            //通知
            number = 3;
            condition3.signal();
        } finally {
            lock.unlock();
        }
    }

    public void print3() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (number !=3){ //while
                condition3.await();
            }
            //干活
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+i);
            }
            //通知
            number = 1;
            condition1.signal();
        } finally {
            lock.unlock();
        }
    }


}
